<?php
/*
 * 栏目分类控制器
 */
class CategoryController extends IsLoginController{
	private $Model;
	//自定执行
	public function __init(){
		parent::__init();
		$this->Model = K('Category');
	}
	public function index(){
		//查询分配数据到页面
		
		$cateInfo = data::tree($this->Model->all(),'category_name','cid','pid');
		$this->assign('cateInfo',$cateInfo);
		$this->display();
	}
	//添加分类
	public function add(){
		
		$cateInfo = data::tree($this->Model->all(),'category_name','cid','pid');
		$this->assign('cateInfo',$cateInfo);
		if(IS_POST){
			if(!$this->Model->addCategory()){
				$this->error($this->Model->error);
			}
			$this->success('添加成功');
		}
		$this->display();
	}
	//添加子分类
	public function addSon(){
		//查询传值
		$cid = Q('get.cid');
		$father =M('category')->where("cid = '{$cid}'")->find();
		$this->assign('father',$father);
		//查询类型
		$type = M('type')->all();
		$this->assign('type',$type);
		//处理添加事件
		if(IS_POST){
			if(!$this->Model->addCategory()){
				$this->error($this->Model->error);
			}
			$this->success('添加成功');
		}
		
		$this->display();
	}
	//批量添加分类
	public function batchAdd(){
		//查询所有栏目信息 传递提供显示		
		$cateInfo = data::tree($this->Model->all(),'category_name','cid','pid');
		$this->assign('cateInfo',$cateInfo);
		if(IS_POST){			
			if(!$this->Model->batchAdd()){
				$this->error($this->Model->error);
			}
			$this->success('栏目添加成功');
		}
		$this->display();
	}
	//修改分类
	public function edit(){
		//查询传值
		$cid = Q('get.cid');
		//分配当前修改栏目信息到页面
		$father =M('category')->where("cid = '{$cid}'")->find();
		$this->assign('father',$father);
		
		//查询类型
		$type = M('type')->all();
		$this->assign('type',$type);
		
		//不能修改为自身栏目和 自身栏目的子集  查询子集 并把自身压入 做不可选		
		$sonCid = $this->getSon($this->Model->all(),$cid);
		$sonCid[]= $cid;
		$sonCid = implode(',', $sonCid);
		$sonCate = $this->Model->where("cid not in ($sonCid)")->all();

		//获取树状栏目 分配到页面
		$cateInfo = data::tree($sonCate,'category_name','cid','pid');
		$this->assign('cateInfo',$cateInfo);
		//处理添加事件
		if(IS_POST){
			
			if(!$this->Model->editCategory()){
				$this->error($this->Model->error);
			}
			$this->success('修改成功');
		}
		$this->display();
	}
	//删除栏目
	public function del(){
		$cid = Q('get.cid',0,'intval');
		//查询是否有子栏目
		$son = $this->Model->where("pid ='{$cid}'")->find();
		if($son){
			$this->error('当前栏目下有子栏目，请删除子栏目后再尝试删除！');
		}
		$this->Model->where("cid='{$cid}'")->delete();
		$this->success('删除成功');
	}
	//异步查询子栏目
	public function ajaxText(){
		$cid = Q('post.cid',0,'intval');
		$data = $this->Model->all();
		//在查找到的所有栏目信息  里查找子集cid
		$sonCid = $this->getSon($data,$cid);
		$this->ajax($sonCid);
	}
	//查询子栏目
	public function getSon($data,$cid){
		static $temp = array();
		foreach($data as $v){
			if($v['pid'] == $cid ){
				$temp[]=$v['cid'];
				$this->getSon($data,$v['cid']);
			}
		}
		return $temp;
	}
	
}
